
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Gateway中的Filter机制 - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>Gateway中的Filter机制 - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "根据文档，Spring Cloud Gateway 的 Filter 机制采用了哪种核心设计模式来组织和执行过滤器？",
    "options": [
      "观察者模式 (Observer Pattern)",
      "单例模式 (Singleton Pattern)",
      "过滤器链模式 (Filter Chain Pattern)，也称为责任链模式",
      "工厂模式 (Factory Pattern)"
    ],
    "correctAnswerIndex": 2,
    "explanation": "文档明确指出，Gateway Filter 机制采用的是基于过滤器链的设计模式。每个请求会按照预设的顺序依次通过一个由多个过滤器组成的链，每个过滤器完成自己的任务后将请求传递给下一个，这正是责任链模式的典型应用。",
    "source": "文档中「Gateway Filter 机制的概述 - 核心思想与设计」部分",
    "hint": "文档描述了请求如何“按照配置依次通过一个过滤器链”。"
  },
  {
    "question": "在 Gateway Filter 的执行流程中，关于 Pre Filter 和 Post Filter 执行顺序的描述，哪一个是正确的？",
    "options": [
      "Pre Filter 和 Post Filter 都按照 'Order' 值的升序执行。",
      "Pre Filter 按升序执行，而 Post Filter 按降序执行。",
      "Pre Filter 按降序执行，而 Post Filter 按升序执行。",
      "执行顺序是随机的，无法保证。"
    ],
    "correctAnswerIndex": 1,
    "explanation": "这是一个关键且容易混淆的知识点。文档中特别说明，在 Pre 阶段，过滤器的执行顺序由 'Order' 属性控制，值越小优先级越高（升序执行）。然而，在 Post 阶段，为了确保逻辑的正确闭环（例如计算请求耗时），过滤器会以相反的顺序执行，即按 'Order' 值的降序执行。",
    "source": "文档中「Gateway Filter 的工作原理 - 过滤器的有序执行」部分",
    "hint": "注意文档中对 Pre 阶段和 Post 阶段执行顺序的对比描述。"
  },
  {
    "question": "如果你需要实现一个对所有通过网关的请求都生效的功能，例如统一的身份认证或日志记录，你应该选择实现哪种类型的自定义过滤器？",
    "options": [
      "局部过滤器 (Route-Specific Filter)",
      "全局过滤器 (Global Filter)",
      "内置过滤器 (Built-in Filter)",
      "响应过滤器 (Response Filter)"
    ],
    "correctAnswerIndex": 1,
    "explanation": "文档将自定义过滤器分为两类。全局过滤器（Global Filters）作用于所有路由，不与特定路由绑定，非常适合实现认证、日志、监控等全局通用逻辑。而局部过滤器（Route-Specific Filters）仅对绑定的特定路由生效。",
    "source": "文档中「Gateway Filter 的工作原理 - 过滤器类型的角色」或「自定义过滤器的实现步骤 - 1. 明确自定义过滤器的类型」部分",
    "hint": "哪种过滤器“作用于所有请求，不与特定路由绑定”？"
  },
  {
    "question": "某微服务的 API 路径从 `/api/user` 迁移到了 `/v2/user-service`。为了兼容旧的客户端请求，网关需要将所有访问 `/api/user` 的请求路径重写为 `/v2/user-service`。使用哪个内置过滤器最适合完成这个任务？",
    "options": [
      "StripPrefix",
      "SetRequestHeader",
      "RewritePath",
      "AddRequestParameter"
    ],
    "correctAnswerIndex": 2,
    "explanation": "RewritePath 过滤器允许使用正则表达式来匹配和替换请求路径的一部分，非常适合这种复杂的路径重写场景。StripPrefix 只能移除路径前缀，SetPath 会完全替换路径，而 AddRequestParameter 用于添加查询参数，均不如此场景下的 RewritePath 灵活和精确。",
    "source": "文档中「Gateway Filter 的内置过滤器 - 核心内置过滤器」部分",
    "hint": "哪个内置过滤器提供了基于正则表达式的路径替换功能？"
  },
  {
    "question": "在实现自定义的 Global Filter 时，除了实现 `GlobalFilter` 接口来定义核心逻辑外，通常还需要实现哪个接口来控制其执行优先级？",
    "options": [
      "`GatewayFilter`",
      "`Ordered`",
      "`Filter`",
      "`Comparable`"
    ],
    "correctAnswerIndex": 1,
    "explanation": "为了控制过滤器在链中的执行顺序，需要实现 `Ordered` 接口并重写 `getOrder()` 方法。该方法返回一个整数，数值越小，过滤器的优先级越高。这是确保复杂逻辑能按预期顺序执行的关键。",
    "source": "文档中「自定义过滤器的实现步骤 - 3. 编写自定义过滤器类」部分",
    "hint": "文档的示例代码中，自定义 Global Filter 类实现了两个接口，一个是 `GlobalFilter`，另一个是？"
  },
  {
    "question": "Gateway Filter 机制能够实现高性能、高并发处理能力的核心技术基础是什么？",
    "options": [
      "基于传统的多线程同步阻塞模型",
      "广泛使用内存缓存来加速响应",
      "基于 Spring WebFlux 的异步非阻塞响应式编程模型",
      "通过批处理机制合并请求"
    ],
    "correctAnswerIndex": 2,
    "explanation": "文档多次强调，Spring Cloud Gateway 及其 Filter 机制是建立在 Spring WebFlux 之上的，采用了基于 Reactor 的响应式编程模型。这种异步非阻塞的方式可以有效利用少量线程处理大量并发请求，避免了线程阻塞带来的资源浪费，从而实现高吞吐和低延迟。",
    "source": "文档中「Gateway Filter 的特点 - 1. 响应式编程模型」或「Gateway Filter 的优缺点 - 优点」部分",
    "hint": "文档提到了一个关键的技术栈，它使得 Gateway Filter 能够“采用非阻塞的方式处理高并发请求”。"
  },
  {
    "question": "在微服务架构中，利用 Gateway Filter 实现对某个 API 的访问频率进行限制，防止因流量突增导致服务崩溃。这属于哪个典型的应用场景？",
    "options": [
      "动态路由",
      "请求认证与鉴权",
      "请求限流",
      "日志记录与监控"
    ],
    "correctAnswerIndex": 2,
    "explanation": "对 API 的访问频率进行控制，例如通过令牌桶算法限制单位时间内的请求数量，是典型的请求限流场景。这可以有效保护后端服务，防止其被恶意攻击或正常流量洪峰冲垮。内置的 `RequestRateLimiter` 过滤器就是为此目的设计的。",
    "source": "文档中「Gateway Filter 的应用场景 - 3. 请求限流」部分",
    "hint": "当需要保护后端服务不被过载时，我们会采取哪种流量控制措施？"
  },
  {
    "question": "根据文档分析，使用 Gateway Filter 机制可能面临的一个主要缺点或挑战是什么？",
    "options": [
      "无法与 Spring Cloud 生态中的其他组件（如 Eureka）集成。",
      "内置过滤器功能过于简单，无法满足大部分需求。",
      "响应式编程模型增加了开发复杂性和调试难度。",
      "无法对请求和响应的 Body 内容进行修改。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "文档在“缺点”部分明确指出，响应式编程（Reactive Programming）虽然带来了性能优势，但也提高了开发和调试的复杂性。对于不熟悉该模型的开发者来说，理解异步数据流、处理错误以及追踪问题都会更具挑战性，学习成本较高。",
    "source": "文档中「Gateway Filter 的优缺点 - 缺点」部分",
    "hint": "文档提到了，对于初学者来说，理解哪种编程模型可能存在“较大的上手难度”？"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  